
# V appendix - Figure A1 : ------------------------------
do_concentration_100_bins<- function( data = test_dt_withProb_cancer) { 
bins_100_died  <- data[,.(cost = sum(UTL_f365d_total_cost ),
                                             adj_cost = sum(UTL_f365d_total_cost)/
                                               (sum( ifelse(DMG_died_within_365d == "0",
                                                            366,
                                                            as.numeric(difftime(DMG_date_of_death_XX,
                                                                                S_index_date_XX, 
                                                                                units = "days"))+1))/(366*.N)) 
),
by = .(
  group = factor(ifelse(DMG_died_within_365d=="1", "Decedent", "Survivor"),
                 levels = c("Decedent", "Survivor")),
  bins = plyr::round_any(prob_for_report, 0.01, floor)
)][order(group,bins)]

bins_100_died[, cumsum :=  rev(cumsum(rev(cost))), by = group ]
bins_100_died[ ,sum_cost  := sum(cost)]
bins_100_died[ ,sum_cum  := cumsum/sum_cost]

bins_100_died[, adj_cumsum :=  rev(cumsum(rev(adj_cost))), by = group ]
bins_100_died[ ,adj_sum_cost  := sum(adj_cost)]
bins_100_died[ ,adj_sum_cum  := adj_cumsum/adj_sum_cost]

write.csv(bins_100_died,"conc_100_bins_death_adj.csv")

pdf("concetration_100_bins_death_adj.pdf", width = 10, height = 7.5)
print(ggplot(data = bins_100_died,
       aes(x=bins,
           y = adj_sum_cum ,
           fill = group)) +
  geom_bar(stat = "identity",
           position = position_stack(reverse = TRUE)) +
  scale_fill_grey()+
  labs(fill = "",
       x = "Initial Prognosis (One-Year Mortality Risk)",
       y = "Share of Spending Accounted for by Individuals with\n Initial Prognosis Greater than the X-Axis Value") + 
  scale_x_continuous(breaks = seq(0, 1, 0.1)) +
  scale_y_continuous(breaks = seq(0, 1, 0.2)) +
  theme(axis.title.x = element_text(size = 16),
        axis.title.y = element_text(size = 16))
)
dev.off()
}
